"use client"

import { useState, useRef, useEffect } from "react"

interface EvolutionStage {
  id: string
  name: string
  period: string
  imageUrl?: string
}

interface EvolutionHistoryProps {
  currentChar: string
}

export function EvolutionHistory({ currentChar }: EvolutionHistoryProps) {
  const [stages, setStages] = useState<EvolutionStage[]>([
    {
      id: 'jiaguwen',
      name: '甲骨文',
      period: '商朝'
    },
    {
      id: 'jinwen',
      name: '金文',
      period: '西周'
    },
    {
      id: 'xiaozhuan',
      name: '小篆',
      period: '秦朝'
    },
    {
      id: 'lishu',
      name: '隶书',
      period: '汉朝'
    },
    {
      id: 'kaishu',
      name: '楷书',
      period: '现代'
    }
  ])

  const fileInputRefs = useRef<{ [key: string]: HTMLInputElement | null }>({})

  // 处理图片上传
  const handleImageUpload = (stageId: string, event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const imageUrl = e.target?.result as string
        setStages(prev => prev.map(stage => 
          stage.id === stageId 
            ? { ...stage, imageUrl }
            : stage
        ))
        
        // 保存到localStorage
        const savedImages = JSON.parse(localStorage.getItem('evolutionImages') || '{}')
        savedImages[`${currentChar}_${stageId}`] = imageUrl
        localStorage.setItem('evolutionImages', JSON.stringify(savedImages))
      }
      reader.readAsDataURL(file)
    }
  }

  // 从localStorage加载图片
  const loadSavedImages = () => {
    const savedImages = JSON.parse(localStorage.getItem('evolutionImages') || '{}')
    setStages(prev => prev.map(stage => ({
      ...stage,
      imageUrl: savedImages[`${currentChar}_${stage.id}`] || stage.imageUrl
    })))
  }

  // 组件加载时恢复图片
  useEffect(() => {
    loadSavedImages()
  }, [currentChar])

  // 删除图片
  const removeImage = (stageId: string) => {
    setStages(prev => prev.map(stage => 
      stage.id === stageId 
        ? { ...stage, imageUrl: undefined }
        : stage
    ))
    
    // 从localStorage删除
    const savedImages = JSON.parse(localStorage.getItem('evolutionImages') || '{}')
    delete savedImages[`${currentChar}_${stageId}`]
    localStorage.setItem('evolutionImages', JSON.stringify(savedImages))
  }

  return (
    <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-amber-50 to-orange-50 rounded-3xl">
      {/* 字形源流时间轴 */}
      <div className="relative w-full max-w-6xl px-8">
        {/* 连接线 */}
        <div className="absolute top-1/2 left-16 right-16 h-1 bg-gradient-to-r from-amber-400 via-orange-500 to-amber-400 rounded-full transform -translate-y-1/2 z-0"></div>
        
        {/* 演变阶段圆圈 */}
        <div className="relative flex justify-between items-center z-10">
          {stages.map((stage, index) => (
            <div key={stage.id} className="flex flex-col items-center">
              {/* 阶段名称 */}
              <div className="mb-6 text-center">
                <h3 className="font-bold text-xl text-amber-700 mb-1">{stage.name}</h3>
                <p className="text-sm text-gray-600">{stage.period}</p>
              </div>
              
              {/* 圆形图片容器 */}
              <div 
                className="relative w-32 h-32 rounded-full border-4 border-white bg-white shadow-xl overflow-hidden cursor-pointer group hover:scale-105 transition-all duration-300"
                onClick={() => fileInputRefs.current[stage.id]?.click()}
              >
                {stage.imageUrl ? (
                  <>
                    <img 
                      src={stage.imageUrl} 
                      alt={`${stage.name}字形`}
                      className="w-full h-full object-cover"
                    />
                    {/* 删除按钮 */}
                    <button
                      onClick={(e) => {
                        e.stopPropagation()
                        removeImage(stage.id)
                      }}
                      className="absolute top-2 right-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      ×
                    </button>
                  </>
                ) : (
                  <div className="w-full h-full flex flex-col items-center justify-center text-gray-400 bg-gray-50">
                    <div className="text-4xl mb-2">📷</div>
                    <p className="text-sm text-center">点击上传<br/>{stage.name}字形</p>
                  </div>
                )}
                
                {/* 上传提示遮罩 */}
                {stage.imageUrl && (
                  <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                    <div className="text-white text-sm font-medium">点击更换</div>
                  </div>
                )}

                {/* 隐藏的文件输入 */}
                <input
                  ref={el => { fileInputRefs.current[stage.id] = el }}
                  type="file"
                  accept="image/*"
                  onChange={(e) => handleImageUpload(stage.id, e)}
                  className="hidden"
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
} 